#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from config import DB


def check_ruoyi_tables():
    try:
        # 使用项目配置连接ruoyi数据库
        conn = DB()

        cursor = conn.cursor()

        # 查看所有表
        print("=== ruoyi数据库中的所有表 ===")
        cursor.execute('SHOW TABLES')
        tables = cursor.fetchall()

        for i, table in enumerate(tables, 1):
            print(f"{i:2d}. {table[0]}")

        print(f"\n总共有 {len(tables)} 个表")

        # 选择几个重要的表查看结构
        important_tables = ['sys_user', 'sys_role', 'sys_menu', 'sys_dept']

        for table_name in important_tables:
            if any(table[0] == table_name for table in tables):
                print(f"\n=== {table_name} 表结构 ===")
                cursor.execute(f'DESCRIBE {table_name}')
                columns = cursor.fetchall()

                print(f"{'字段名':<20} {'类型':<20} {'是否为空':<10} {'键':<10} {'默认值':<15} {'额外':<15}")
                print("-" * 90)

                for col in columns:
                    field, type_, null, key, default, extra = col
                    default_str = str(default) if default is not None else 'NULL'
                    print(f"{field:<20} {type_:<20} {null:<10} {key:<10} {default_str:<15} {extra:<15}")

        cursor.close()
        conn.close()

        print("\n数据库连接已关闭")

    except Exception as e:
        print(f"连接数据库时出错: {e}")


if __name__ == "__main__":
    check_ruoyi_tables()
